import java.util.Arrays;

/**
* @description: 743. 网络延迟时间
* @author hewei
* @date 2022/8/19 14:07
* @version 1.0
*/

public class NetworkDelayTime {

    public static void main(String[] args) {
        NetworkDelayTime networkDelayTime = new NetworkDelayTime();
        int[][] nums = {{1,2,1}, {2,1,3}};
        System.out.println(networkDelayTime.networkDelayTime(nums, 2, 2));
    }

    public int networkDelayTime(int[][] times, int n, int k) {
        final int INF = Integer.MAX_VALUE / 2;
        int[][] g = new int[n][n];
        boolean[] visited = new boolean[n];
        int[] dist = new int[n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(g[i], INF);
        }
        for (int[] t : times) {
            g[t[0] - 1][t[1] - 1] = t[2];
        }
        Arrays.fill(dist, INF);
        dist[k - 1] = 0;
        for (int i = 0; i < n; i++) {
            int temp = -1;
            for (int j = 0; j < n; j++) {
                if (!visited[j] && (temp == -1 || dist[j] < dist[temp])) temp = j;
            }
            visited[temp] = true;
            for (int j = 0; j < n; j++) {
                dist[j] = Math.min(dist[j], dist[temp] + g[temp][j]);
            }
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans = Math.max(ans, dist[i]);
        }
        return ans == INF ? -1 : ans;
    }
}